#include "mainwnd.h"
#include "ui_mainwnd.h"

//////////////////////////////////////////////////////////////////////////
//
MainWnd* MainWnd::ms_instance = nullptr;


//////////////////////////////////////////////////////////////////////////
//
MainWnd::MainWnd(const QString & strUrl, QWidget *parent)
    : ExtendWindow(parent)
    , m_strFirstUrl(strUrl)
    , ui(new Ui::MainWnd)
{
    //
    ui->setupUi(this);

    //
    init();

    //保存第一个实例
    if (ms_instance == nullptr)
    {
        ms_instance = this;
    }
}

MainWnd::~MainWnd()
{
    //
    if (ms_instance == this)
    {
        ms_instance = nullptr;
    }

    //
    delete ui;
}

void MainWnd::closeEvent(QCloseEvent *event)
{
    //
    m_tab->closeAllTab();

    //
    __super::closeEvent(event);
}

void MainWnd::firstShowedEvent(QEvent * event)
{
    //
    newTab(m_strFirstUrl);
}

void MainWnd::init()
{
    //
    m_tab = new WebTabWidget(this);
    ui->layCentral->addWidget(m_tab);

    connect(m_tab, &WebTabWidget::newMainWnd, this, &MainWnd::onNewMainWnd);
    connect(m_tab, &WebTabWidget::btNewClicked, this, &MainWnd::onNew);
    connect(m_tab, &WebTabWidget::btMenuClicked, this, &MainWnd::onMenu);
    connect(m_tab, &WebTabWidget::btMinClicked, this, &MainWnd::onMin);
    connect(m_tab, &WebTabWidget::btMaxClicked, this, &MainWnd::onMax);
    connect(m_tab, &WebTabWidget::btCloseClicked, this, &MainWnd::onExit);
    connect(m_tab, &WebTabWidget::allTabClosed, this, &MainWnd::onAllTabClosed);

    //
    initMenu();
}

void MainWnd::initMenu()
{
    //main menu
    m_muMain = new QMenu(this);

    m_atClose = new QAction(("退出"), m_muMain);
    m_atClose->setStatusTip(("退出"));
    m_muMain->addAction(m_atClose);

    //
    connect(m_atClose, &QAction::triggered, this, &MainWnd::onClose);
}


void MainWnd::onClose()
{
    this->close();
}

void MainWnd::onMenu()
{
    m_muMain->exec(QCursor::pos());
}

void MainWnd::onExit()
{
    this->close();
}

void MainWnd::onMax()
{
    if (this->isMaximized())
    {
        this->showNormal();
    }
    else
    {
        this->showMaximized();
    }
}

void MainWnd::onMin()
{
    this->showMinimized();
}


void MainWnd::onNew()
{
    newTab();
}


void MainWnd::onAllTabClosed()
{
    this->close();
}


void MainWnd::loadUrl(const QUrl & url)
{
    m_tab->curWebWnd()->loadUrl(url);
}

void MainWnd::load(const QString & strUrl)
{
    m_tab->curWebWnd()->loadUrl(strUrl);
}

WebWnd * MainWnd::newTab(const QString & strUrl, bool current, int index)
{
    return m_tab->newTab(strUrl, current, index);
}

void MainWnd::onNewMainWnd(QString strUrl)
{
    MainWnd * wnd = (new MainWnd(strUrl));
    wnd->setAttribute(Qt::WA_DeleteOnClose);
    wnd->show();
}



